//
//  KLUserInformationTableViewController.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 16/4/28.
//  Copyright © 2016年 陈宾鹏. All rights reserved.
//

#import "KLUserInformationTableViewController.h"
#import "HemaConst.h"
#import "UIImageView+WebCache.h"
#import "FMDBTool.h"
#import "HemaConst.h"
#import "HemaFunction.h"
#import "KLHttpAPI.h"
#import "UIActionSheet+Blocks.h"
#import "RIButtonItem.h"
#import "YPpickViewController.h"
#import "KLHelp.h"
#import "KLRevisePasswordViewController.h"
#import "JRToast.h"
#import "HemaFunction.h"
#import "Masonry.h"

#import "RBDatePickerView.h" // datePickerView
#import "KLManageGesturePasswordViewController.h"
@interface KLUserInformationTableViewController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIAlertViewDelegate>
{
    UIImagePickerController *picker;
}
@property (nonatomic,strong) NSMutableDictionary *userInforDic;
@property (nonatomic,strong) UIImageView *userImageView;
@property (nonatomic,strong) UIImageView *imageFadeView;
@property (nonatomic,strong) UIImageView *imageBackView;

@property (nonatomic,strong) UIImage *imageFade;
@property (nonatomic,strong) UIImage *imageBack;
@property (nonatomic,strong) UIImage *userImage;

@property (nonatomic,strong) NSMutableDictionary *submitUserDic;//个人资料

@property (assign) NSInteger state;

@property (nonatomic, strong) RBDatePickerView *rb_PivkerView; // 出身年月datePickerView

@end

static int _chooseImage;
static NSArray *_dateBaseArray;

@implementation KLUserInformationTableViewController
-(UIImage *)imageFade{
    if(!_imageFade){
        _imageFade = [UIImage imageNamed:@"identy1"];
    }
    return _imageFade;
}

-(UIImage *)imageBack{
    if(!_imageBack){
        _imageBack = [UIImage imageNamed:@"identy2"];
    }
    return _imageBack;
}

-(UIImage *)userImage{
    if(!_userImage){
        _userImage = [UIImage imageNamed:@"我的_on"];
    }
    return _userImage;
}

-(NSMutableDictionary *)submitUserDic{
    if(!_submitUserDic){
        _submitUserDic = [NSMutableDictionary dictionary];
    }
    return _submitUserDic;
}

- (RBDatePickerView *)rb_PivkerView {
    if (!_rb_PivkerView) {
        _rb_PivkerView = [[RBDatePickerView alloc] init];
        [_rb_PivkerView rb_setUpDefaultDateWithYear:2000 month:6 day:20]; // 设置默认日期
    }
    return _rb_PivkerView;
}

-(void)viewDidAppear:(BOOL)animated{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        picker = [[UIImagePickerController alloc] init];
        picker.allowsEditing = YES;
        picker.delegate = self;
    });
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
     _chooseImage = 0;
    _dateBaseArray = [NSArray arrayWithObjects:@"userid",@"username",@"email",@"password",@"nickname",@"mobile",@"avatar",@"validflag",@"score",@"feeaccount",@"deviceid",@"devicetype",@"lastloginversion",@"lastlogintime",@"imgurl0",@"imgurl1",@"state",@"birthday",@"imgurl2",@"sex",@"token",nil];
    //拿到数据库数据
    [FMDBTool openDataBase];
    self.userInforDic = [FMDBTool selectDataBase];
    
    //当state为1时，section0部分不可编辑
    self.state = ((NSString *)[self.userInforDic objectForKey:@"state"]).integerValue;
    
    //给submit赋初始值
    [self.submitUserDic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"token"] forKey:@"token"];
    [self.submitUserDic setObject:[self.userInforDic objectForKey:@"nickname"] forKey:@"nickname"];
    [self.submitUserDic setObject:[self.userInforDic objectForKey:@"birthday"] forKey:@"birthday"];
    [self.submitUserDic setObject:[self.userInforDic objectForKey:@"sex"] forKey:@"sex"];

    //设置表头视图
    [self headSet];
    [self.tableView reloadData];
    //设置导航栏
    [self navSet];
    
    //设置表尾视图
//    [self footSet];
    [self setFootWithNothing];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(section == 0){
        return 3;
    }else if(section == 1){
        return 3;
    }else{
        return 2;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell;
    if(indexPath.section == 0){
         cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell0"];
        if(indexPath.row == 0){
            NSString *str = [self.userInforDic objectForKey:@"nickname"];
            cell.textLabel.text = @"姓名";
            cell.detailTextLabel.text = str;
            if(self.state != 1){
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }
        }else if(indexPath.row == 1){
            NSString *str = [self.userInforDic objectForKey:@"sex"];
            cell.textLabel.text = @"性别";
            cell.detailTextLabel.text = str;
            if(self.state != 1){
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }
        }else if(indexPath.row == 2){
            NSString *str = [self.userInforDic objectForKey:@"birthday"];
            cell.textLabel.text = @"出生年月";
            cell.detailTextLabel.text = [str hasPrefix:@"0"] ? @"" : str;
            if(self.state != 1){
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }
        }
    }
    else if (indexPath.section == 1){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell1"];
        if(indexPath.row == 0){
            NSString *mobileStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"];
            NSString *darkMobile = [NSString stringWithFormat:@"%@****%@",[mobileStr substringToIndex:3],[mobileStr substringFromIndex:7]];
            cell.textLabel.text = @"更换绑定手机号";
            cell.detailTextLabel.text = darkMobile;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        else if (indexPath.row == 1){
            cell.textLabel.text = @"修改密码";
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        else{
            cell.textLabel.text = @"手势密码管理";
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
            
    }
    else if(indexPath.section == 2){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell2"];
        if(indexPath.row == 0){
            cell.textLabel.text = @"审核状态";
            if(self.state != 1){
                cell.detailTextLabel.text = @"审核尚未通过 ！";
                cell.detailTextLabel.textColor = [UIColor redColor];
            }else{
                cell.detailTextLabel.text = @"审核已通过";
                cell.detailTextLabel.textColor = [UIColor greenColor];
            }
        }else if(indexPath.row == 1){
            cell.textLabel.text = @"自动登录";
            UISwitch *autoLoginSwitch = [[UISwitch alloc]initWithFrame:CGRectMake(UI_View_Width-70, 6, 0, 0)];
            autoLoginSwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"isAutoLogin"];
            
            [autoLoginSwitch addTarget:self action:@selector(isAutoLogin:) forControlEvents:UIControlEventValueChanged];
            [cell addSubview:autoLoginSwitch];
        }else{
//            cell.textLabel.text = @"上传身份验证信息:";
        }
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.font = [UIFont systemFontOfSize:16];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:16];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    //设置分区高
    if (section == 0) {
        return 0;
    }
    
    return 20;
}

//点击cell触发
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0 && self.state != 1){
        if(indexPath.row == 0){
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"姓名修改" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"修改",nil];
            alert.alertViewStyle = UIAlertViewStylePlainTextInput;
            [alert show];
        }else if(indexPath.row == 1){
            UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"选择性别"
                                                       cancelButtonItem:[RIButtonItem itemWithLabel:@"取消" action:nil]
                                                  destructiveButtonItem:[RIButtonItem itemWithLabel:@"女" action:^{
                                                                            [self.userInforDic setObject:@"女" forKey:@"sex"];
                                                                            [self.submitUserDic setObject:@"女" forKey:@"sex"];
                                                                            [self.tableView reloadData];
                                                                        }]
                                                       otherButtonItems:[RIButtonItem itemWithLabel:@"男" action:^{
                                                                            [self.userInforDic setObject:@"男" forKey:@"sex"];
                                                                            [self.submitUserDic setObject:@"男" forKey:@"sex"];
                                                                            [self.tableView reloadData];
                                                                        }], nil];
            [sheet showInView:self.tableView];
        }else if(indexPath.row == 2){
//            YPpickViewController *ypVC  = [[YPpickViewController alloc]init];
//            ypVC.calendarblock = ^(YPpickViewModel *model){
//                NSString *timeStr = [NSString stringWithFormat:@"%@-%@-%@",model.year,model.moth,model.day];
//                [self.submitUserDic setObject:timeStr forKey:@"birthday"];
//                [self.userInforDic setObject:timeStr forKey:@"birthday"];
//                [self.tableView reloadData];
//            };
//            [self.navigationController pushViewController:ypVC animated:YES];
            
            // 弹出日期选择器
            [self.rb_PivkerView rb_show];
            
            // 选择日期
            __weak typeof(self) weakSelf = self;
            self.rb_PivkerView.sureButtonClickBlock = ^(NSString *year, NSString *month, NSString *day) {
                NSString *timeStr = [NSString stringWithFormat:@"%@-%@-%@",year,month,day];
                
                [weakSelf.submitUserDic setObject:timeStr forKey:@"birthday"];
                [weakSelf.userInforDic setObject:timeStr forKey:@"birthday"];
                
                [weakSelf.tableView reloadData];
            };
        }
    }
    else if(indexPath.section == 1){
        if(indexPath.row == 0){
            UIStoryboard* mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
            KLRevisePasswordViewController *revisePasswordVC = [mainStoryboard instantiateViewControllerWithIdentifier:@"revisePasswordVC"];
            [self.navigationController pushViewController:revisePasswordVC animated:YES];
        }
        else if(indexPath.row == 1){
            UIStoryboard* mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
            KLRevisePasswordViewController *revisePasswordVC = [mainStoryboard instantiateViewControllerWithIdentifier:@"revisePhoneVC"];
            [self.navigationController pushViewController:revisePasswordVC animated:YES];
        }
        else  {
            // 管理手势密码
            KLManageGesturePasswordViewController *gesturePwdVC = [[KLManageGesturePasswordViewController alloc] init];
            [self.navigationController pushViewController:gesturePwdVC animated:YES];
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}

#pragma mark -设置导航栏和标头视图
-(void)navSet{
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:21]}];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:(float)8/255 green:(float)128/255 blue:(float)181/255 alpha:1];
    [self.navigationController.navigationBar setTranslucent:NO];
    self.navigationItem.title = @"个人信息";
    
    //左侧返回按钮
    UIButton *backbutton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 10, 20)];
    [backbutton setBackgroundImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backbutton addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backbutton];
    
    //右侧提交按钮
    UIButton *submitbutton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    [submitbutton setTitle:@"提交" forState:UIControlStateNormal];
    [submitbutton addTarget:self action:@selector(submit:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:submitbutton];
}

-(void)headSet{
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, 90)];
    headView.backgroundColor = [UIColor whiteColor];
    self.tableView.tableHeaderView = headView;
    
    self.userImageView = [[UIImageView alloc]init];
    self.userImageView.layer.masksToBounds = YES;
    self.userImageView.layer.cornerRadius = 30;
    [self.userImageView sd_setImageWithURL:[[NSUserDefaults standardUserDefaults] objectForKey:@"avatar"] placeholderImage:self.userImage];
    self.userImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapImage = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapImage:)];
    [self.userImageView addGestureRecognizer:tapImage];
    [headView addSubview:self.userImageView];
    [self.userImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(60);
        make.left.mas_equalTo(10);
        make.centerY.equalTo(headView);
    }];
    
    UILabel *nickNameLabel = [[UILabel alloc]init];
    nickNameLabel.text = [self.userInforDic objectForKey:@"username"];
    nickNameLabel.textAlignment = NSTextAlignmentLeft;
    nickNameLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:18];
    [headView addSubview:nickNameLabel];
    [nickNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.userImageView).with.offset(75);
        make.right.equalTo(headView).with.offset(-10);
        make.centerY.equalTo(self.userImageView);
    }];
    
    UIView *sperateView = [[UIView alloc]initWithFrame:CGRectMake(0, headView.frame.size.height-1, headView.frame.size.width, 0.7)];
    sperateView.backgroundColor = [UIColor lightGrayColor];
    sperateView.alpha = 0.5;
    [headView addSubview:sperateView];
}

-(void)footSet{
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, 100)];
    self.tableView.tableFooterView = footView;
    
    self.imageFadeView = [[UIImageView alloc]initWithFrame:CGRectMake(30, 5, 90, 70)];
    self.imageFadeView.image = self.imageFade;
    self.imageFadeView.tag = 1;
    self.imageFadeView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapIdentity1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapIdentity1:)];
    [self.imageFadeView addGestureRecognizer:tapIdentity1];
    self.imageBackView = [[UIImageView alloc]initWithFrame:CGRectMake(UI_View_Width-120, 5, 90, 70)];
    self.imageBackView.image = self.imageBack;
    self.imageBackView.tag = 2;
    self.imageBackView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapIdentity2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapIdentity2:)];
    [self.imageBackView addGestureRecognizer:tapIdentity2];
    
    [footView addSubview:self.imageFadeView];
    [footView addSubview:self.imageBackView];
    
}
// 去掉cell格子
- (void)setFootWithNothing {
    UIView *footView = [[UIView alloc] init];
    self.tableView.tableFooterView = footView;
}

#pragma mark -方法体内方法
-(void)tapImage:(id)sender{
    UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:@"修改头像" delegate:self cancelButtonTitle:Button_Cancel destructiveButtonTitle:nil otherButtonTitles:Button_Albums,Button_Camera, nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    [actionSheet showInView:self.tableView];
}

-(void)tapIdentity1:(UITapGestureRecognizer *)tap{
    if(self.state == 1){
        return ;
    }
    
    UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:@"选取身份证正面照" delegate:self cancelButtonTitle:Button_Cancel destructiveButtonTitle:nil otherButtonTitles:Button_Albums,Button_Camera, nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    [actionSheet showInView:self.tableView];
}

-(void)tapIdentity2:(UITapGestureRecognizer *)tap{
    if(self.state == 1){
        return ;
    }
    
    UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:@"选取身份证反面照" delegate:self cancelButtonTitle:Button_Cancel destructiveButtonTitle:nil otherButtonTitles:Button_Albums,Button_Camera, nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    [actionSheet showInView:self.tableView];
}

-(void)isAutoLogin:(UISwitch *)isAutoSwtich{
    [[NSUserDefaults standardUserDefaults] setBool:isAutoSwtich.on forKey:@"isAutoLogin"];
}

static dispatch_semaphore_t sem;
#pragma mark -点击提交
-(void)submit:(id)sender{
    dispatch_queue_t queue_t = dispatch_queue_create("singnalControl", NULL);
    sem = dispatch_semaphore_create(1);
    dispatch_async(queue_t, ^{
        NSLog(@"点击提交,参数为:%@",self.submitUserDic);
        [KLHelp showHUDAddedTo:self.view title:@"正在提交" details:nil animated:YES];
        [KLHttpAPI submitUserInformationWithUserDic:self.submitUserDic completionHandler:^(NSString *responseString){
            [KLHelp hideAllHUDsForView:self.view animated:YES];
            dispatch_semaphore_signal(sem);
        } errorHandler:^(NSString *error) {
            [KLHelp hideAllHUDsForView:self.view animated:YES];
        }];
    });
    
    dispatch_async(queue_t, ^{
        dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
        //上传图片
        if(![self.userImageView.image isEqual:self.userImage]){
            [self submitImage:@"1"];
        }
        if(![self.imageFadeView.image isEqual:self.imageFade] && ![self.imageBackView.image isEqual:self.imageBack]){
            
            //删除身份证信息
//            [self submitImage:@"2"];
//            [self submitImage:@"3"];
        }
    });
    
    dispatch_async(queue_t, ^{
        //更新个人信息数据
        dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
        [self refreshUserInformation];
    });
    
}

#pragma mark -actionSheet代理
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex == 0){
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];
        [self presentViewController:picker animated:YES completion:nil];
    }else if(buttonIndex == 1){
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];
    }
    
    if([actionSheet.title isEqualToString:@"修改头像"]){
        _chooseImage = 1;
    }else if([actionSheet.title isEqualToString:@"选取身份证正面照"]){
        _chooseImage = 2;
    }else if([actionSheet.title isEqualToString:@"选取身份证反面照"]){
        _chooseImage = 3;
    }
}

#pragma mark -图片选择器的代理
- (void)imagePickerController:(UIImagePickerController *)picker
        didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
    if(_chooseImage == 1){
        self.userImageView.image = image;
    }else if (_chooseImage == 2){
        self.imageFadeView.image = image;
    }else if (_chooseImage == 3){
        self.imageBackView.image = image;
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
}


-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -alertView的代理
-(void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex == 1){
        //得到输入框
        UITextField *tf=[alertView textFieldAtIndex:0];
        if([HemaFunction xfunc_check_strEmpty:tf.text]){
            [JRToast showWithText:@"姓名不能为空"];
            return ;
        }
        [self.userInforDic setObject:tf.text forKey:@"nickname"];
        [self.submitUserDic setObject:tf.text forKey:@"nickname"];
    }
    [self.tableView reloadData];
}

#pragma mark -刷新个人信息数据
-(void)refreshUserInformation{
    [KLHelp showHUDAddedTo:self.view title:@"更新个人资料" details:nil animated:YES];
    [KLHttpAPI requestUserInformationWithToken:[[NSUserDefaults standardUserDefaults] objectForKey:@"token"] userID:[self.userInforDic objectForKey:@"userid"] completionHandler:^(NSString *responseString) {
        NSLog(@"个人信息返回成功：%@",responseString);
        dispatch_semaphore_signal(sem);
        NSDictionary *responseDic = [KLHelp dictionaryWithJsonString:responseString];
        NSDictionary *inforDic = [responseDic objectForKey:@"infor"][0];
        
        NSString *isTrue = [responseDic objectForKey:@"success"];
        if(isTrue.integerValue == 1){
            [KLHelp hideAllHUDsForView:self.view animated:YES];
            [JRToast showWithText:@"数据更新成功"];
            //将得到的用户信息存入数据库
            [FMDBTool openDataBase];
            [FMDBTool deleteDataBase];
            for (int i = 0; i < _dateBaseArray.count; i++) {
                if(i == 0){
                    [FMDBTool insertDataBaseWithKey:_dateBaseArray[i] value:[inforDic objectForKey:@"id"]];
                }else{
                    [FMDBTool insertDataBaseWithKey:_dateBaseArray[i] value:[inforDic objectForKey:[_dateBaseArray objectAtIndex:i]]];
                }
            }
            //拿到登录信息的数据
            self.userInforDic = [FMDBTool selectDataBase];
            
            NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
            [userDefault setObject:[self.userInforDic objectForKey:@"username"] forKey:@"userName"];
            [userDefault setObject:[self.userInforDic objectForKey:@"mobile"] forKey:@"phoneNumber"];
        }
        [self.tableView reloadData];
    } errorHandler:^(NSString *error) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        [JRToast showWithText:@"数据更新失败"];
    }];
}

#pragma mark -上传图片
-(void)submitImage:(NSString *)keyType{
    NSData *temData;
    if(keyType.integerValue == 1){
        temData = UIImageJPEGRepresentation(self.userImageView.image, 0.3);
    }else if(keyType.integerValue == 2){
        temData = UIImageJPEGRepresentation(self.imageFadeView.image, 0.3);
    }else if(keyType.integerValue == 3){
        temData = UIImageJPEGRepresentation(self.imageBackView.image, 0.3);
    }
    
    [KLHttpAPI submitImageDataWithToken:[[NSUserDefaults standardUserDefaults] objectForKey:@"token"] imageData:temData keyType:keyType completionHandler:^(NSString *responseString) {
        NSLog(@"返回数据：%@",responseString);
        NSDictionary *dic = [KLHelp dictionaryWithJsonString:responseString];
        NSString *isSuccess = [dic objectForKey:@"success"];
        if(isSuccess.integerValue == 1){
            if([keyType isEqualToString:@"1"]){
                [[NSUserDefaults standardUserDefaults] setObject:[dic objectForKey:@"msg"] forKey:@"avatar"];
                NSLog(@"%@",[dic objectForKey:@"msg"]);
                [[NSNotificationCenter defaultCenter] postNotificationName:@"imageUpdate" object:nil userInfo:nil];
            }
        }else{
            [JRToast showWithText:[dic objectForKey:@"msg"]];
        }
        
        dispatch_semaphore_signal(sem);
    } errorHandler:^(NSString *error) {
    }];
}

-(void)doBack:(id)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end
